package com.inspinia.config.common.config;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ResourceBundle;

/**
 * shiro配置
 * 优先使用配置中心的配置，如果没有配置文件使用本地配置
 * @author Veblen
 */
@Slf4j
@Data
public class ShiroPropConfig {

    /**
     * shiro.properties的配置数据
     */
    public static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("shiro");
    public static String getString(String key) {
        return RESOURCE_BUNDLE.getString(key);
    }

    public static Long timeout = Long.valueOf(getString("inspinia.shiro.session.timeout"));
    public static String loginUrl = getString("inspinia.shiro.loginUrl");
    public static String logoutUrl = getString("inspinia.shiro.logoutUrl");
    public static String successUrl = getString("inspinia.shiro.successUrl");
    public static String unauthorizedUrl = getString("inspinia.shiro.unauthorizedUrl");


    /**
     *  监听配置
     * @param changeEvent
     */
    @ApolloConfigChangeListener("shiro")
    public void shiroChange(ConfigChangeEvent changeEvent){
        log.info("Changes for namespace {}", changeEvent.getNamespace());
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            log.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
                    change.getPropertyName(), change.getOldValue(), change.getNewValue(),
                    change.getChangeType());
            if ("inspinia.shiro.session.timeout".equals(change.getPropertyName())) {
                timeout = Long.valueOf(change.getNewValue());
            }
            if ("inspinia.shiro.loginUrl".equals(change.getPropertyName())) {
                loginUrl = change.getNewValue();
            }
            if ("redis.timeout".equals(change.getPropertyName())) {
                logoutUrl = change.getNewValue();
            }
            if ("redis.password".equals(change.getPropertyName())) {
                successUrl = change.getNewValue();
            }
            if ("redis.expire".equals(change.getPropertyName())) {
                unauthorizedUrl = change.getNewValue();
            }
        }
    }
}
